package com.shop.web;

import com.shop.entity.User;
import com.shop.service.IUserService;
import com.shop.service.impl.UserServiceImpl;
import com.shop.util.*;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet("/user")
public class UserServlet extends BaseServlet {

    protected String loginView(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        return "redirect:/pages/user/login.jsp";
    }

    protected String registerView(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        return "redirect:/pages/user/register.jsp";
    }

    protected String check(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        IUserService service = new UserServiceImpl();
        String username = req.getParameter("username");
        if (username != null) {
            List<User> list = service.selectAllUser();
            for (User user : list) {
                if (username.equals(user.getUsername())){
                    return "1";
                }
            }
        }
        return "0";
    }


    protected String register(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        User user = WebUtils.getBean(new User(), req.getParameterMap());
        if (user.getUpassword() == null || user.getUpassword().trim().equals("")){
            req.setAttribute("password","密码不能为空");
            return "forward:/pages/user/register.jsp";
        }else if (user.getUsername() == null || user.getUsername().trim().equals("")){
            req.setAttribute("username","用户名不能为空");
            return "forward:/pages/user/register.jsp";
        }else if (!req.getParameter("reupassword").equals(user.getUpassword())){
            req.setAttribute("repassword","两次密码不相同！");
            return "forward:/pages/user/register.jsp";
        }else if (user.getEmail() == null || user.getEmail().trim().equals("")){
            req.setAttribute("email","邮箱不能为空");
            return "forward:/pages/user/register.jsp";
        }else if (!(user.getEmail().matches("^[a-z0-9A-Z]+[- | a-z0-9A-Z . _]+@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-z]{2,}$"))){
                req.setAttribute("email","邮箱格式不正确");
                return "forward:/pages/user/register.jsp";
        }else if(user.getUsex() == null || user.getUsex().trim().equals("")){
            req.setAttribute("sex","性别不能不勾选");
            return "forward:/pages/user/register.jsp";
        }else{
            user.setUpassword(MD5Utils.md5(user.getUpassword()));
            user.setUstatus(Constants.ACTIVE_FAIL);//常量是0，未激活
            user.setCode(RandomUtils.createActive());//随机数
            user.setUrole(Constants.ROLE_CUSTOMER);//0用户设置权限
            IUserService service = new UserServiceImpl();
            boolean bool = service.insertUser(user);
            System.out.println(user.getEmail());

            if (bool) {
                System.out.println("--------------");
                EmailUtils.sendEmail(user);//里面的方法对code又进行一次编码
               return "forward:/pages/user/registerSuccess.jsp";
            }
            return "forward:/pages/user/login.jsp";
        }
    }

    protected String active(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String c = req.getParameter("c");//获得code码
        String code = null;
        if (c != null){
            code  = Base64Utils.decode(c);//解码
        }
        IUserService userService = new UserServiceImpl();
        boolean b = userService.updateUser(code);

        return "forward:/pages/user/login.jsp";
    }

    protected String login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String auto = req.getParameter("auto");
        String code = (String) req.getSession().getAttribute("code");
        String username = req.getParameter("username");
        if (username == null){
            req.setAttribute("username","用户名不能为空");
            return "forward:pages/user/login.jsp";
        }
        String pwd = req.getParameter("password");
        if (pwd == null){
            req.setAttribute("pwd","密码不能为空");
            return "forward:pages/user/login.jsp";
        }
        String password = MD5Utils.md5(pwd);//密码
        String loginCode = req.getParameter("code");
        IUserService userService = new UserServiceImpl();
        User user = userService.selectUserByName(username);
        if (user.getUstatus() != Constants.ROLE_ADMIN){
            req.setAttribute("status","当前账号未激活！");
            return "forward:pages/user/login.jsp";
        }

        if (StrUtils.empty(code)){//code不为空
            if (code.equalsIgnoreCase(loginCode)){
                if (user != null){
                    if (user.getUpassword().equals(password)){
                        req.getSession().setAttribute("user",user);
                        if (auto != null){
                            if (auto.equals("on")){
                                Cookie cookie = new Cookie("name",user.getUsername());
                                cookie.setPath("/");
                                cookie.setMaxAge(60*60*24*14);
                                resp.addCookie(cookie);
                            }
                        }
                        return "forward:pages/client/index.jsp";
                    }
                }
                req.setAttribute("error","用户名或密码错误");
                return "forward:pages/user/login.jsp";
            }
            req.setAttribute("codeError","验证码错误");
            return "forward:pages/user/login.jsp";
        }
        req.setAttribute("codeError","验证码不能为空");
        return "forward:pages/user/login.jsp";
    }


    protected String quit(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cookie[] cookies = req.getCookies();
        if (cookies != null) {
            Cookie cookie = new Cookie("name", null);
            cookie.setMaxAge(0);
            cookie.setPath("/");
            resp.addCookie(cookie);
        }
        HttpSession session = req.getSession();
        if (session != null || session.getAttribute("user") != null){
            session.removeAttribute("user");
            return "redirect:/pages/client/index.jsp";
        }

        return "redirect:/pages/client/index.jsp";
    }


    protected String autoLogin(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cookie[] cookies = req.getCookies();
        IUserService service = new UserServiceImpl();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("name")) {
                    String name = cookie.getValue();
                    User user = service.selectUserByName(name);
                    req.getSession().setAttribute("user", user);
                    return "forward:pages/client/index.jsp";
                }
            }
        }
        return "forward:pages/client/index.jsp";
    }
}
